package pg.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Reader;
import java.util.StringTokenizer;

import pg.objetosbasicos.Ponto;
import pg.objetosbasicos.Triangulo;
import pg.objetosbasicos.Vetor;

public class LoadData {
	public int numPontos;
	public Ponto[] pontos;
	public Vetor[] normaisPontos;
	
	public int numTriagulos;
	public Triangulo[] triagulos;	
	public Vetor[] normaisTriangulos;
	
	private String path;	

	public LoadData(String path) {
		this.path = path;			
	}		
	
	public void Load() throws ArquivoInvalidoException {
		try {
			Reader reader = new FileReader(path);
			BufferedReader br = new BufferedReader(reader);
			StringTokenizer st = new StringTokenizer(br.readLine(), " ");
			String[] str = this.toArray(st);
			
			this.numPontos = Integer.parseInt(str[0]);
			this.pontos = new Ponto[this.numPontos];
			
			this.numTriagulos = Integer.parseInt(str[1]);			
			this.triagulos = new Triangulo[this.numTriagulos];

			for (int i = 0; i < this.numPontos; i++) {
				Ponto tmp = new Ponto();
				st = new StringTokenizer(br.readLine().replace(',', '.'), " ");
				str = this.toArray(st);
				tmp.x = Float.parseFloat(str[0]);
				tmp.y = Float.parseFloat(str[1]);
				tmp.z = Float.parseFloat(str[2]);
				pontos[i] = tmp;
			}
			
			for (int i = 0; i < this.numTriagulos; i++) {
				Triangulo tmp = new Triangulo();
				st = new StringTokenizer(br.readLine(), " ");
				str = this.toArray(st);
				tmp.vertice1 = Integer.parseInt(str[0]) - 1;
				tmp.vertice2 = Integer.parseInt(str[1]) - 1;
				tmp.vertice3 = Integer.parseInt(str[2]) - 1;
				triagulos[i] = tmp;
			}
		} catch (Exception e) {
			throw new ArquivoInvalidoException();
		}
	}
	
	private String[] toArray(StringTokenizer st) {
		String[] result = new String[st.countTokens()];
		for(int i = 0; st.hasMoreElements(); i++) {
			result[i] = st.nextToken();
		}
		return result;
	}
}
